package com.ruoyi.ai.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.ai.domain.UserVO;
import com.ruoyi.ai.service.IExtendUserService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.sms.SmsSendService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @description:ExtendUserServiceImpl
 * @author: caoes
 * create:2023/6/29 11:04
 **/
@Service
public class ExtendUserServiceImpl implements IExtendUserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SmsSendService smsSendService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SysRegisterService sysRegisterService;

    @Override
    public void sendSmsCode(HttpServletRequest request, String mobile) {

        String cacheKey = "SMS_CODE_"+ mobile;
        if (StringUtils.isNotBlank(redisTemplate.opsForValue().get(cacheKey))){
            Long seconds = redisTemplate.opsForValue().getOperations().getExpire(cacheKey);
            throw new RuntimeException("请" + seconds + "秒后重新获取");
        }
//        String cmsCode = RandomUtil.randomNumbers(6);
//        smsSendService.sendSmsCode(mobile, cmsCode);
        String cmsCode = "000000";
        // 设置缓存
        redisTemplate.opsForValue().set(cacheKey, cmsCode, 5 * 60, TimeUnit.SECONDS);
    }

    @Override
    public AjaxResult login(HttpSession httpSession, String mobile, String validCode) {
        // check validCode
        checkSmsCode(mobile, validCode);

        SysUser sysUser = iSysUserService.selectUserByUserName(mobile);
        if (!Objects.isNull(sysUser)) {
            return login(sysUser, httpSession);
        } else {
            return registerAndLogin(mobile, httpSession);
        }
    }

    @Override
    public SysUser getUserInfo() {
        return iSysUserService.selectUserById(SecurityUtils.getUserId());
    }

    private AjaxResult login(SysUser sysUser, HttpSession httpSession) {
        AjaxResult ajax = AjaxResult.success();
        String token = sysLoginService.login(sysUser);
        Map<String, Object> returnMap = new HashMap<>();

        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(sysUser, userVO);

        returnMap.put(Constants.TOKEN, token);
        returnMap.put("userInfo",userVO);
        ajax.put("data",returnMap);
        httpSession.setAttribute("user",sysUser);
        return ajax;
    }

    private AjaxResult registerAndLogin(String mobile, HttpSession httpSession) {
        SysUser sysUserRegister = new SysUser();
        sysUserRegister.setNickName("企智小秘_" + RandomUtil.randomString(6));
        sysUserRegister.setUserName(mobile);
        sysUserRegister.setPhonenumber(mobile);
        sysUserRegister.setQuantity(5000);
        sysUserRegister.setSex("0");
        sysUserRegister.setRemark("手机号码注册");
        String token = sysRegisterService.register(sysUserRegister);

        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(sysUserRegister, userVO);

        AjaxResult ajax = AjaxResult.success();
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put(Constants.TOKEN, token);
        returnMap.put("userInfo",userVO);
        ajax.put("data",returnMap);
        httpSession.setAttribute("user",sysUserRegister);
        return ajax;
    }

    private void checkSmsCode(String mobile, String validCode) {
        String cacheKey = "SMS_CODE_"+ mobile;
        String smsCode = redisTemplate.opsForValue().get(cacheKey);
        if (null == smsCode) {
            throw new RuntimeException("请重新获取验证码");
        }
        if (!StrUtil.equals(smsCode, validCode)) {
            throw new RuntimeException("验证码不正确");
        }
        redisTemplate.delete(cacheKey);
    }
}
